package br.com.salaodebeleza.domain.converter;

import javax.el.ValueExpression;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;
import javax.faces.model.SelectItem;

import br.com.salaodebeleza.domain.TbCliente;
import br.com.salaodebeleza.view.TbAgendaEditMB;

@FacesConverter(value = "tbClienteConverter")
public class TbClienteConverter implements Converter {

	public String getAsString(
			FacesContext arg0, UIComponent arg1, Object arg2) {
		if (arg0 == null){throw new NullPointerException("context");}
		if (arg1 == null){throw new NullPointerException("component");}
		return ((TbCliente)arg2).getId() + "";
	}
	public Object getAsObject(
			FacesContext arg0, UIComponent arg1, String arg2) {
		if (arg0 == null){throw new NullPointerException("context");}
		if (arg1 == null){throw new NullPointerException("component");}
		FacesContext ctx = FacesContext.getCurrentInstance();
		ValueExpression vex =
				ctx.getApplication().getExpressionFactory()
				.createValueExpression(ctx.getELContext(),
						"#{tbAgendaEditMB}",TbAgendaEditMB.class);
		TbAgendaEditMB tbAgenda = (TbAgendaEditMB)vex.getValue(ctx.getELContext());
		TbCliente tbCliente = null;
		try {
			for(SelectItem i : tbAgenda.getTbClientes()){
				if( (((TbCliente)i.getValue()).getId() + "").equals(arg2) ){
					tbCliente = (TbCliente) i.getValue();
				}
			}
		} catch( NumberFormatException e ) {
			FacesMessage message =
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Unknown value", "This is not a car number!" );
			throw new ConverterException( message );
		}
		if( tbCliente == null ) {
			FacesMessage message = new FacesMessage(
					FacesMessage.SEVERITY_ERROR,
					"Unknown value", "The grupo is unknown!" );
			throw new ConverterException( message );
		}
		return tbCliente;
	}

}
